<?php
include_once './config/config.php';

if ($_POST) {
    // todo 判断验证码
    if ($_POST['action'] == 'check') {
        $val = $_POST['val'];

        if ($val != $_SESSION['imgcode']) {
            error("验证码错误");
            exit;
        }
        success("验证码正确");
    }

    // todo 封装表单数据
    $formData = [
        "username" => $_POST['username'],
    ];
    // todo 查询数据库表
    $findSql = "SELECT * FROM `pre_admin` WHERE `username` = '{$formData['username']}' ";
    $data = query($findSql);

    // todo 判断用户是否存在
    if (!$data) {
        error("用户不存在");
        exit;
    }

    // todo 封装表单数据
    $formData['password'] = md5(trim($_POST['password']) . $data['salt']);

    // todo 输入密码不正确
    if ($formData['password'] != $data['password']) {
        error("密码不正确");
        exit;
    }

    // todo 用id + 密码盐 => md5
    $loginAdmin = md5($data['id'] . $data['salt']);

    // todo 登录成功后储存登录信息,注意开启cookie
    setcookie('loginAdmin', $loginAdmin);

    // todo 成功登录
    $msg = "登录成功，欢迎回来" . $formData['username'];
    success($msg);
    exit;
}
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <?php include_once('common/meta.php'); ?>
    <title>login</title>
</head>

<div class="navbar">
    <div class="navbar-inner">
        <a class="brand" href="index.html"><span class="second">Admin</span></a>
    </div>
</div>

<div class="row-fluid">
    <div class="dialog">
        <div class="block">
            <p class="block-heading">登录</p>
            <div class="block-body">
                <form method="POST" id="login_form">
                    <div class="form-group">
                        <label>用户名</label>
                        <input type="text" class="span12" name="username" required>
                    </div>

                    <div class="form-group">
                        <label>密码</label>
                        <input type="password" class="span12" name="password" required>
                    </div>

                    <div class="form-group" style="margin-bottom:20px;">
                        <label>验证码</label>
                        <input type="text" class="span9" name="imgcode" required style="margin-bottom: 0;">
                        <img src="config/imgcode.php" onclick="this.src = `config/imgcode.php`" alt="" id="imgcode">
                        <span id="tips"></span>
                    </div>

                    <button type="submit" class="btn btn-lg btn-primary btn-block">登录</button>
                    <div class="clearfix"></div>
                </form>
            </div>
        </div>
    </div>
</div>

<script src="assets/lib/jquery-1.7.2.min.js" type="text/javascript"></script>
<script src="assets/lib/bootstrap/js/bootstrap.js"></script>
<script type="text/javascript">
    $("[rel=tooltip]").tooltip();
    $(function() {
        $('.demo-cancel-click').click(function() {
            return false;
        });
    });

    $("#login_form").on("submit", function(e) {
        e.preventDefault();
        let formData = $(this).serialize();
        $.ajax({
            type: "post",
            url: "login.php",
            data: formData,
            dataType: "json",
            success: function(res) {
                if (res.code === 0) {
                    alert(res.msg);
                } else if (res.code === 1) {
                    alert(res.msg);
                    // console.log(res);
                    // sessionStorage.setItem('data', JSON.stringify(res.data));
                    location.href = "index.php";
                }
            },
            error: function(err) {
                console.log(err);
            }
        });
    });

    $("input[name='imgcode']").change(function(e) {
        e.preventDefault();
        let val = $(this).val();
        $.ajax({
            type: "post",
            url: "login.php",
            data: {
                val,
                action: 'check'
            },
            dataType: "json",
            success: function(res) {
                if (res.code === 1) {
                    $("#tips").html(res.msg).css({
                        "color": "green"
                    });
                } else {
                    $("#tips").html(res.msg).css({
                        "color": "red"
                    });
                }
            },
            error: function(err) {
                console.log(err);
            }
        });
    })
</script>

</body>

</html>